package com.muc.socket;

import com.muc.handler.MainViewHandlerToService;
import com.muc.util.DBUtil;
import com.muc.view.LoginView;
import com.muc.view.MainView;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClinet2 {
    private Selector selector;
    SocketChannel socketChannel;
    private static MainView gui;//主操作
    public NIOClinet2(){
        try {
            this.selector = Selector.open();
            this.socketChannel = SocketChannel.open();//打开
            this.socketChannel.connect(new InetSocketAddress("127.0.0.1",5555));

        } catch (IOException e) {
            System.out.println(new RuntimeException("初始客户端出错"));
            e.printStackTrace();
        }

    }
    public void listen() throws IOException {
        while (true) {// 轮询访问selector
            selector.select();
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {//遍历所有就绪Channel
                SelectionKey key = (SelectionKey) ite.next();
                ite.remove();// 删除已选的key,以防重复处理
                if (key.isConnectable()) {//有链接事件发生
                    SocketChannel channel = (SocketChannel) key.channel();
                    if(channel.isConnectionPending()){// 真正完成连接
                        channel.finishConnect();
                    }
                    channel.configureBlocking(false);// 设置成非阻塞
//                    sendFirstMsg();
                    //给服务端发送信息
                    System.out.println("Client is ready to send msg...");
                    channel.write(ByteBuffer.wrap(new String("I am client").getBytes()));
                    //给Channel设置为可读以继续读取数据
                    channel.register(this.selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
//                    write(key);
                    write();
                    System.out.println("执行到conn");
                } else if(key.isWritable()){
                    System.out.println("执行到iswriteable 方法");
                    write();
                    //                    write(key);
                }else if (key.isReadable()) {
                    read(key);
                }/*else if(key.isWritable()){
                    write(key);
                }*/
            }
        }
    }

//    private void write(SelectionKey key) throws IOException {
        private void write() throws IOException {
            while (true) {
            System.out.println("传输写入数据");
//            SocketChannel channel = (SocketChannel) key.channel();
            String[] lines = new String[2];
            lines[0] = lines[1] = "";
            while (gui.isAdd() || gui.isDel() || gui.isUpdate() || gui.isSearch() || gui.isPrePage() || gui.isNextPage()) {
                if (gui.isAdd()) {//给服务器发送增加指令
                    lines[0] = "增加";
                    lines[1] = "#-1";
                    gui.setAdd(false);
                } else if (gui.isDel()) {//删除可以删除多行
                    lines[0] = "删除";
                    for (int carId : gui.getSelectedCarIds()) {
                        lines[1] = "#" + carId;//# 做分隔符 spilt切割
                    }
                    gui.setDel(false);
                } else if (gui.isUpdate()) {//修改只能一次改一行
                    lines[0] = "修改";
                    int[] selectedCarIds = gui.getSelectedCarIds();
                    lines[1] = selectedCarIds[0] + "";
                    gui.setUpdate(false);
                } else if (gui.isSearch()) {
                    lines[0] = "查询";
                    lines[1] = "#-1";
                    gui.setSearch(false);
                } else if (gui.isPrePage()) {
                    lines[1] = "#-1";
                    lines[0] = "上一页";
                    gui.setPrePage(false);
                } else if (gui.isNextPage()) {
                    lines[0] = "下一页";
                    lines[1] = "#-1";
                    gui.setNextPage(false);
                }
                //推送数据到服务器
                System.out.println("客户端传递信息为:" + lines[0] + "和" + lines[1]);
                socketChannel.write(ByteBuffer.wrap(lines[0].getBytes()));
//            channel.write(ByteBuffer.wrap(lines[1].getBytes()));
                socketChannel.write(ByteBuffer.wrap(lines[1].getBytes()));

            }
        }
    }

    public void sendFirstMsg() throws IOException {
//        ByteBuffer byteBuffer1 = ByteBuffer.wrap("测试一对多C/S NIO service 端传输数据开始!".getBytes());
//        socketChannel.write(byteBuffer1);//将缓冲器中的数据写入SocketChannel
        System.out.println("数据已经写给服务器");
    }

    public void read(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();//返回一个SocketChannel
        ByteBuffer buffer = ByteBuffer.allocate(50);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("Server received msg："+msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outBuffer);//读取客户传递的数据

        //将SocketCjannel中的数据存放到缓冲器
        /*ByteBuffer byteBuffer2 = ByteBuffer.allocate(1024);
        int len;
        while((len = socketChannel.read(byteBuffer2)) != -1){
            System.out.println("客户端接收回写数据");
            byteBuffer2.flip();//从写模式转换为读模式
            System.out.println(new String(byteBuffer2.array(),0,len));
            byteBuffer2.clear();
        }
        socketChannel.close();*/

    }

    public static void main(String[] args) throws IOException {

        NIOClinet2 clinet = new NIOClinet2();
        clinet.sendFirstMsg();
        gui = new LoginView().mainView;
        MainViewHandlerToService.mainView = gui;
/*        System.out.println(MainViewHandlerToService.mainView);
        System.out.println(gui.getPageNow()+"jjjj");*/
//        new MainView();
        clinet.write();//------
        clinet.listen();
        System.out.println("wwww");
        DBUtil.close();


    }
}